package com.eastedu.util;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;

/**
 * The type Data source utils.
 * @author zhangzhishuai
 */
@Slf4j
public class DataSourceUtils {

    /**
     * Executes a Runnable task with the data source specified by the @DS annotation on the given class.
     *
     * @param runnable the task to execute
     * @param clazz    the class with the @DS annotation
     */
    public static void executeWithDataSource(Runnable runnable, Class<?> clazz) {
        DS dsAnnotation = clazz.getAnnotation(DS.class);
        String dataSource = dsAnnotation == null ? null : dsAnnotation.value();
        DynamicDataSourceContextHolder.push(dataSource);
        try {
            runnable.run();
        } catch (Exception e) {
            log.error("执行失败：", e);
        } finally {
            DynamicDataSourceContextHolder.poll();
        }
    }
}